package com.minivision.sdktestdemo.model;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;

import com.minivision.sdktestdemo.bean.MusicBean;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by devtang on 2016/4/8.
 */
public class MusicProvider extends Provider<MusicBean> implements UriInfoGetter {
    private WeakReference<Context> mContext;
    private ContentResolver mMusicResolver;
    private static final String ALBUM_COVER_URI = "content://media/external/audio/albumart";

    private static final String[] sDataCols = {
            MediaStore.Audio.Media.ARTIST,
            MediaStore.Audio.Media.ALBUM,
            MediaStore.Audio.Media.DURATION,
            MediaStore.Audio.Media.TITLE,
            MediaStore.Audio.Media.SIZE,
            MediaStore.Audio.Media.DATA,
            MediaStore.Audio.Media.ALBUM_ID,
            MediaStore.Audio.Media._ID,
    };
    private static MusicProvider sMusicProvider;

    public static MusicProvider getInstance(Context context) {
        if (sMusicProvider == null) {
            synchronized (MusicProvider.class) {
                if (sMusicProvider == null) {
                    sMusicProvider = new MusicProvider(context);
                }
            }
        }
        return sMusicProvider;
    }

//    public static void release() {
//        sMusicProvider.releaseContext();
//        sMusicProvider = null;
//    }

//    public void releaseContext() {
//        mContext = null;
//        mMusicResolver = null;
//    }

//    public void setContext(Context context) {
//        mContext = context;
//        mMusicResolver = mContext.getContentResolver();
//    }

    private MusicProvider(Context context) {
        mContext = new WeakReference<Context>(context);
        if (mContext.get() != null) {
            mMusicResolver = mContext.get().getContentResolver();
        }
    }

    @Override
    public void update() {
        //查询音乐的信息,但是如果有新的音乐,则这个暂时不会更新
        Cursor musicCur = mMusicResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                sDataCols, MediaStore.Audio.Media.DURATION + " > ?", new String[]{"60000"}, null);
        while (musicCur.moveToNext()) {
            mList.add(new MusicBean(musicCur));
            Uri uri = ContentUris.withAppendedId(Uri.parse(ALBUM_COVER_URI), mList.get(mList.size() - 1).getmAlbumId());
            mList.get(mList.size() - 1).setmPicUri(uri);
        }
        sort(mList);
        setChanged(true);
    }


    @Override
    public int remove(MusicBean data, boolean isDeletedFlag) {
        mList.remove(data);
        int num = removeFromBase(data, isDeletedFlag);
        setChanged(true);
        return num;
    }

    private int removeFromBase(MusicBean data, boolean isDeletedFlag) {
        int num = mMusicResolver.delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                "?=" + MediaStore.Audio.Media._ID, new String[]{data.getmId() + ""});
        if (isDeletedFlag) {
            //同时删除本地文件
            File f = new File(data.getmPath());
            if (f.exists()) {
                num = f.delete() ? num : -1;
            }
        }
        return num;
    }

    private int removeFromBase(List<MusicBean> beans, boolean isDeletedFlag) {
        int nums = 0;
        for (MusicBean bean : beans) {
            int num = removeFromBase(bean, isDeletedFlag);
            nums = num == -1 ? -1 : nums + num;
        }
        return nums;
    }

    public int remove(List<MusicBean> list, boolean isDeletedFlag) {
        Set<MusicBean> set = new HashSet<>(list);
        List<MusicBean> temp = new ArrayList<>(mList.size() - list.size());
        int nums = 0;
        for (MusicBean bean : mList) {
            if (!set.contains(bean)) {
                temp.add(bean);
            }
        }
        nums = removeFromBase(list, isDeletedFlag);
        mList.clear();
        mList.addAll(temp);
        setChanged(true);
        return nums;
    }

    public int update(MusicBean src) {
        ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.Audio.Media.ALBUM, src.getmAlbumName());
        contentValues.put(MediaStore.Audio.Media.ARTIST, src.getmSingerName());
        contentValues.put(MediaStore.Audio.Media.DISPLAY_NAME, src.getmMusicName());
        setChanged(true);
        return mMusicResolver.update(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                contentValues, "?=" + MediaStore.Audio.Media._ID, new String[]{src.getmId() + ""});
    }

    public int update(int index) {
        MusicBean data = mList.get(index);
        setChanged(true);
        return update(data);
    }

    @Override
    public String getKey(MusicProvider provider, int position) {
        return null;
    }

    @Override
    public String getUri(int position) {
        return mList.get(position).getmPath();
    }

    @Override
    public int uriSize() {
        return size();
    }
}
